package com.sihai.ehr.web.action.leave;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.*;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.*;
import com.sihai.ehr.utils.DateUtil;
import com.sihai.ehr.web.AuthorityManager;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.SearchFormPojo;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * author: wxn
 * @since 13-4-26 20:10
 * 离职申请Action
 */
@Results({
        @Result(name = "add", location = "/WEB-INF/pages/leave/leave_office_input.jsp"),
        @Result(name = "list-user", location = "/WEB-INF/pages/leave/leave_office_list_user.jsp"),
        @Result(name = "list", location = "/WEB-INF/pages/leave/leave_office_list.jsp"),
        @Result(name = "audit", location = "leave_office_audit.jsp"),
        @Result(name = "main", location = "/WEB-INF/pages/leave/leave_office_main.jsp"),
        @Result(name = "hr-audit-input", location = "leave_office_hr_audit_input.jsp"),
        @Result(name = "procedure-print", location = "leave_procedure_print.jsp")
})
public class LeaveOfficeApplyAction extends EHRAction {
    @BeanInject
    private LeaveOfficeApplyService leaveOfficeApplyService;
    @BeanInject
    private LeaveOfficeProjectService leaveOfficeProjectService;
    @BeanInject
    private EmployeeService employeeService;
    @BeanInject
    private UserService userService;
    @BeanInject
    private OrganizationService organizationService;

    private LimitedList<LeaveOfficeApply> applys;
    private LeaveOfficeApply apply;

    private List<List<LeaveOfficeApplyAuditing>> audits;
    private List<Organization> organizations;

    private List<LeaveOfficeProject> projects;

    private List<EmployeeinfoEducation> educations; //员工教育列表
    private List<EmployeeinfoTrain> trains; //员工培训列表
    private List<EmployeeWorkExperience> workExperiences; //员工工作经历列表
    private List<EmployeeinfoFamily> families; //员工家庭关系列表

    private String type;

    private boolean showDateInputSearch = true;
    protected SearchFormPojo searchFormPojo;

    private boolean result;

    //员工操作部分(不作权限处理)
    @Action("/public/leave-office-apply-list")
    public String findByUser() throws Exception {
        Long userId = getCurrentUserId();
        //超级管理员不允许申请离职
        if(userId == AuthorityManager.super_admin_long_id){
            return "list-user";
        }
        applys = leaveOfficeApplyService.findLeaveOfficeApplyByUser(userId);
        if(applys != null && !applys.isEmpty()){
            apply = applys.get(applys.size()-1); //得到最后一次申请
        }
        return "list-user";
    }

    @Action("/public/leave-office-apply-input")
    public String toAdd() throws Exception {
        Long userId = getCurrentUserId();
        //超级管理员不允许申请离职
        if(userId == AuthorityManager.super_admin_long_id){
            return "list-user";
        }
        if(apply != null && apply.getId() != null){
            apply = leaveOfficeApplyService.get(apply.getId());
        }
        return "add";
    }

    //保存
    @Action("/public/leave-office-apply-save")
    public String save() throws Exception {
        if(apply != null){
            apply.setLeaveDate(DateUtil.createDate(getParameter("apply_leaveDate"), "yyyy-MM-dd"));
            if(apply.getId() == null){
                Long userId = getCurrentUserId();
                EmployeeinfoWork work = null;
                if(userId > 0){
                    User user = userService.getUser(userId);
                    if(user != null){
                        work = user.getWork();
                    }
                }
                apply.setOrganization(work.getOrganization().getTopOrganization());
                apply.setWork(work); //如果是超级管理员操作，则work为null
                apply.setHrStatus(AuditStatus.wait_audit);
                apply.setStatus(AuditStatus.wait_audit);
                leaveOfficeApplyService.save(apply);
            } else {
                LeaveOfficeApply a = leaveOfficeApplyService.get(apply.getId());
                if(a != null){
                    a.setLeaveDate(apply.getLeaveDate());
                    a.setLeaveReason(apply.getLeaveReason());
                    leaveOfficeApplyService.save(a);
                }
            }
        }
        return findByUser();
    }

    @Action("/public/leave-office-apply-delete")
    public String delete() throws Exception {
        if(apply != null && apply.getId() != null){
            leaveOfficeApplyService.delete(apply.getId());
            apply = null;
        }
        return findByUser();
    }


    //======================================================
    //管理员操作部分
    @Action("/leave/apply-hr-audit-main")
    public String mainHrAudit() throws Exception {
        listAction = "/leave/apply-list.xhtml?type=hr_audit";
        listTitle = "HR审核";
        main();
        return "main";
    }
    @Action("/leave/apply-audit-main")
    public String mainAudit() throws Exception {
        listAction = "/leave/apply-list.xhtml?type=audit";
        listTitle = "员工离职审核";
        main();
        return "main";
    }
    @Action("/leave/apply-list-main")
    public String mainList() throws Exception {
        listAction = "/leave/apply-list.xhtml?type=list";
        listTitle = "员工离职浏览";
        main();
        return "main";
    }
    //员工资料管理-离职员工资料
    @Action("/employee/resign")
    public String mainEmployeeList() throws Exception {
        listAction = "/leave/apply-list.xhtml?type=e_list";
        listTitle = "离职员工资料";
        main();
        return "main";
    }
    @Action("/leave/procedures-main")
    public String mainProcedure() throws Exception {
        listAction = "/leave/apply-list.xhtml?type=procedure";
        listTitle = "离职手续办理";
        main();
        return "main";
    }
    private void main() throws Exception {
        showChildOrg = true;
        organizations = organizationService.findChildren(null, true, null, null);
        if (organizations != null && organizations.size() > 0) {
        	if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
            organizationId = organizations.get(0).getId();
        }
    }

    @Action("/leave/apply-list")
    @Override
    public String execute() throws Exception {
        if(StringUtils.equals(type, "hr_audit")){
            applys = leaveOfficeApplyService.findLeaveOfficeApplyForHrList(organizationId, searchFormPojo, createLimit(), createSorter());
        }else if(StringUtils.equals(type, "audit")){
            applys = leaveOfficeApplyService.findLeaveOfficeApplyForAudit(organizationId, searchFormPojo, createLimit(), createSorter());
        }else{
            applys = leaveOfficeApplyService.findLeaveOfficeApplyForList(organizationId, searchFormPojo, createLimit(), createSorter());
        }
        this.paging(applys);
        this.setPageUrl("leave/apply-list.xhtml");
        return "list";
    }

    //进入HR审核输入页面
    @Action("/leave/apply-hr-audit-input")
    public String hrAuditInput() throws Exception {
        if(apply == null){
            return mainHrAudit();
        }
        apply = leaveOfficeApplyService.get(apply.getId());
        if(apply == null){
            return mainHrAudit();
        }
        return "hr-audit-input";
    }
    //HR审核
    @Action("/leave/apply-hr-audit-save")
    public String hrAuditSave() throws Exception {
        if(apply == null){
            return mainHrAudit();
        }
        apply = leaveOfficeApplyService.get(apply.getId());
        if(apply == null){
            return mainHrAudit();
        }
        //{"hr_audit_result": check_value, "leave_reason":$("#leave_reason").val(), "stay_date":stay_date, "stay_way":$("#stay_way").val(), "apply.id":"${apply.id}"};
        LeaveOfficeApplyHrAuditInfo info = new LeaveOfficeApplyHrAuditInfo();
        info.setLeaveOfficeApply(apply);
        info.setAgree(Boolean.parseBoolean(getParameter("hr_audit_result")));
        info.setLeaveReason(getParameter("leave_reason"));
        info.setStayDate(DateUtil.createDate(getParameter("stay_date"), "yyyy-MM-dd"));
        info.setStayWay(getParameter("stay_way"));
        leaveOfficeApplyService.saveLeaveOfficeApplyHrAuditInfo(info);

        return mainHrAudit();
    }

    //离职手续办理
    @Action("/leave/procedure-print")
    public String procedurePrint()throws Exception{
        if(apply == null){
            return mainProcedure();
        }
        apply = leaveOfficeApplyService.get(apply.getId());
        if(apply == null){
            return mainProcedure();
        }
        projects = leaveOfficeProjectService.findByTopOrganization(apply.getOrganization().getId(), null, null);
        return "procedure-print";
    }

    @Action("/leave/apply-audit")
    public String toAudit() throws Exception {
        if(apply == null || apply.getId() == null){
            return mainAudit();
        }
        apply = leaveOfficeApplyService.get(apply.getId());
        if(apply == null || apply.getWork() == null){
            return mainAudit();
        }

        EmployeeinfoBase base = apply.getWork().getBaseId();
        educations = employeeService.getEducationList(base, null, null);
        trains = employeeService.getTrainList(base, null, null);
        workExperiences = employeeService.getWorkExperienceList(base, null, null);
        families = employeeService.getEmployeeFamilyList(base, null, null);

        //得到当前审核历史记录(没有就先保存一个审核流程次数)
        audits = leaveOfficeApplyService.findLeaveOfficeApplyAuditing(apply.getId());
        if(audits == null || audits.isEmpty()){
            leaveOfficeApplyService.saveLeaveOfficeApplyAuditingProcess(apply.getId());
            audits = leaveOfficeApplyService.findLeaveOfficeApplyAuditing(apply.getId());
        }
        //检查当前登录用户是否可以审核当前结点
        if(apply.getWork() != null && audits != null && !audits.isEmpty()){
            checkCanAudit(apply.getWork().getDuty(), audits.get(audits.size()-1));
        }
        currentAuditType = AuditType.audit_leave_office.toString();

        return "audit";
    }

    //离职，更新员工资料表中的状态
    @Action(value = "/ajax/leave-office-apply-finish", results = { @Result(name = "success", type = "json", params = {"root", "result" }) })
    public String leave() throws Exception {
        if(apply != null && apply.getId() != null && apply.getId() > 0){
            try {
                leaveOfficeApplyService.leave(apply);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return SUCCESS;
    }

    public LeaveOfficeApply getApply() {
        return apply;
    }

    public void setApply(LeaveOfficeApply apply) {
        this.apply = apply;
    }

    public LimitedList<LeaveOfficeApply> getApplys() {
        return applys;
    }

    public List<List<LeaveOfficeApplyAuditing>> getAudits() {
        return audits;
    }

    public List<Organization> getOrganizations() {
        return organizations;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<EmployeeinfoEducation> getEducations() {
        return educations;
    }

    public List<EmployeeinfoTrain> getTrains() {
        return trains;
    }

    public List<EmployeeWorkExperience> getWorkExperiences() {
        return workExperiences;
    }

    public List<EmployeeinfoFamily> getFamilies() {
        return families;
    }

    public List<LeaveOfficeProject> getProjects() {
        return projects;
    }

    public boolean isShowDateInputSearch() {
        return showDateInputSearch;
    }

    public SearchFormPojo getSearchFormPojo() {
        return searchFormPojo;
    }

    public void setSearchFormPojo(SearchFormPojo searchFormPojo) {
        this.searchFormPojo = searchFormPojo;
    }

    public boolean isResult() {
        return result;
    }
}
